import redis
import logging
from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from logging.handlers import RotatingFileHandler
from flask_wtf.csrf import generate_csrf, CSRFProtect

db = SQLAlchemy()
rs = None  # type: redis.StrictRedis


def setup_log(config_mode):
    logging.basicConfig(level=config_mode.LOG_LEVEL)
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    formatter = logging.Formatter("%(levelname)s %(filename)s:%(lineno)d %(message)s")
    file_log_handler.setFormatter(formatter)
    logging.getLogger().addHandler(file_log_handler)


def create_app(config_mode):
    setup_log(config_mode)
    app = Flask(__name__)
    app.config.from_object(config_mode)

    global db, rs
    db = SQLAlchemy(app)
    # decode_responses设置自动解码
    rs = redis.StrictRedis(host=config_mode.REDIS_HOST, port=config_mode.REDIS_PORT, decode_responses=True)

    Session(app)
    # 增加csrf保护,意味着,以后遇到POST PUT DELETE请求,服务器会自动获取获取,并对比
    CSRFProtect(app)

    @app.after_request
    def after_request(response):
        csrf_token = generate_csrf()
        response.set_cookie("csrf_token", csrf_token)
        return response

    # 增加模板过滤器
    from info.utils.common import do_index_class
    app.add_template_filter(do_index_class, "rank_class")

    from info.modules.index import index_blue
    app.register_blueprint(index_blue)

    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)

    from info.modules.news import news_blue
    app.register_blueprint(news_blue)

    from info.modules.user import user_blue
    app.register_blueprint(user_blue)

    from info.modules.admin import admin_blue
    app.register_blueprint(admin_blue)

    return app
